Skip to content

SQL-932: Introduce shared parsed-items layer - #40067

Merged
SangJunBak merged 12 commits into
mainfrom
jun/type-relations
Dec 2, 2026
Merged

SangJunBak merged 12 commits into
mainfrom
jun/type-relations

Conversation

@SangJunBak

@SangJunBak SangJunBak commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor
  • Adds mz_catalog_state, a materialized view over mz_catalog_raw that filters out audit log entries, so that our other builtin relations don't have to hydrate from the audit log each time.
  • On top of it we add mz_catalog_items, a materialized view that decodes each item's DDL once, plus a narrow indexed view mz_catalog_item_metadata that excludes the DDL text so we don't store text-heavy fields in memory.
    • It holds every catalog item with an Item record: user items, including temporary ones, and runtime-alterable builtins such as mz_internal.mz_analytics. It carries global_id and ephemeral_owner_session because readers need them (mz_kafka_sources reads global_id, and mz_tables and mz_views derive a temporary item's schema from ephemeral_owner_session).
    • Items decode with parse_catalog_create_sql, as the relations that read mz_catalog_raw do today. A create_sql that fails to decode therefore errors mz_catalog_items and every reader. Raising the error per row through mz_unsafe.mz_error_if_null waits on SQL-795, since its evaluation order is not guaranteed.
  • Adds mz_builtin_object_mappings, an indexed view over the builtin GidMapping records. It leaves out runtime-alterable builtins, which mz_catalog_items already holds, so a reader combining the two lists each object once.
    For an example of how these are intended to be used, this is the definition of mz_types for a later PR in the stack:
WITH
    user_types AS (
        SELECT
            id,
            oid,
            schema_id,
            name,
            COALESCE(mz_unsafe.mz_error_if_null(details, decode_error)->>'category', '') AS category,
            owner_id,
            privileges,
            create_sql,
            redacted_create_sql
        FROM mz_internal.mz_catalog_items
        WHERE type = 'type'
    ),
    builtin_types AS (
        SELECT
            m.id,
            t.oid,
            s.id AS schema_id,
            t.name,
            t.category,
            '{MZ_SYSTEM_ROLE_ID}' AS owner_id,
            t.privileges,
            NULL::text AS create_sql,
            NULL::text AS redacted_create_sql
        FROM mz_internal.mz_builtin_types t
        JOIN mz_internal.mz_builtin_object_mappings m
            ON m.schema_name = t.schema_name AND m.name = t.name AND m.object_type = {object_type}
        JOIN mz_catalog.mz_schemas s ON s.name = t.schema_name AND s.database_id IS NULL
    )
SELECT * FROM user_types
UNION ALL
SELECT * FROM builtin_types",
            object_type = gid_mapping_object_type(CatalogItemType::Type),
        )

Motivation

We introduce these shared materialized views such that we can eventually replace our builtin materialized views with views built on top of them. Removing the other builtin mvs will come in a followup PR.

Part of SQL-932

Verification

In followup PRs, we'll start building our builtin relations on these shared mvs. It seems unnecessary to create individual SLTs for these relations given these will be tested in the SLTs of downstream builtin relations

@SangJunBak
SangJunBak force-pushed the jun/type-relations branch 2 times, most recently from 187e43c to b493cc1 Compare November 11, 2026 18:47
@SangJunBak
SangJunBak force-pushed the jun/type-relations branch 2 times, most recently from 48c6fac to 8560f45 Compare November 17, 2026 08:58
@linear-code

linear-code Bot commented Nov 17, 2026

Copy link
Copy Markdown

SQL-932

@SangJunBak SangJunBak changed the title draft: Implement type builtin relations SQL-932: Introduce shared parsed-items layer Nov 17, 2026
@SangJunBak
SangJunBak marked this pull request as ready for review November 17, 2026 10:56
@SangJunBak
SangJunBak requested review from a team as code owners November 17, 2026 10:56
@ggevay
ggevay self-requested a review November 17, 2026 11:10
@SangJunBak
SangJunBak added this pull request to stack #40844 November 17, 2026 12:16
@aljoscha

Copy link
Copy Markdown
Contributor

We introduce these shared materialized views such that we can eventually replace our builtin materialized views with views built on top of them. Removing the other builtin mvs will come in a followup PR. We do

What's up with the end there? 🤔

@ggevay ggevay left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some comments inline. The important ones are the SQL-948 blocker, the mz_error_if_null stuff, and the item fields that readers need.

SUPPORT_SELECT,
};

// TODO(SQL-932): every builtin relation but `mz_catalog_state` and the audit

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, there is SQL-948, which I think we should treat as a blocker for this PR: in a 0dt upgrade, a new builtin MV such as mz_catalog_items, and everything that reads it, only hydrates after promotion.

With #40843 on top, those readers include the 12 catalog-server indexes that depend on mz_types, such as mz_objects_ind, mz_show_columns_ind and pg_type_all_databases_ind. (Shipping the readers a release later would avoid this problem on Cloud, but self-managed upgrades can skip releases.)

@ggevay ggevay Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a draft PR for SQL-948:
#40903
I'll try to undraft it today.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, will undraft it tomorrow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No worries and thanks for working on it to unblock me!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#40903 has merged, so this is unblocked.

Comment thread src/catalog/src/builtin/mz_internal.rs Outdated
access: vec![],
ontology: None,
});
/// Every user-defined catalog item.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Temporary items and mz_internal.mz_analytics (s851) are Item rows too, so they show up here:

Suggested change
/// Every user-defined catalog item.
/// Every catalog item that has an `Item` record: user items, including temporary ones, and
/// runtime-alterable builtins such as `mz_internal.mz_analytics`.

Comment thread src/catalog/src/builtin/mz_internal.rs Outdated
Comment on lines +90 to +92
/// A relation reading this filters on `type` and if a row's DDL fails to parse,
/// it populates the column `details` as null and `decode_error` with an error message. Readers of this
/// should raise the error through `mz_unsafe.mz_error_if_null`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mz_error_if_null would be a nice thing to use here in theory, but unfortunately mz_error_if_null is fraught with evaluation order issues.

So I'd suggest not using it in this PR: mz_catalog_items could decode with parse_catalog_create_sql, as the relations that read mz_catalog_raw do today. A row that doesn't decode then fails every reader of the layer, much like it fails the relations that parse every item today, and try_decode_catalog_create_sql isn't needed.

For example, a specific issue here would be that mz_error_if_null only fires when a query evaluates the column it wraps. With a user view of the shape described here (WHERE type = 'source', mz_error_if_null(details, decode_error)->>'cluster_id') and one bad source row:

  • SELECT * fails, but SELECT id and count(*) return the bad row without an error.
  • With an index on the view, every peek fails, including lookups of good rows. SQL-495: Convert the type system tables to catalog views #40843's mz_types is such an indexed view (mz_types_ind).
  • WHERE mz_error_if_null(details, decode_error) IS NOT NULL is optimized away, since the function never returns NULL.

For reference, mz_error_if_null's known issues, open and closed:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah that's unfortunate, but makes sense!

SELECT
mz_internal.parse_catalog_id(data->'key'->'gid') AS id,
(data->'value'->>'oid')::oid AS oid,
mz_internal.parse_catalog_id(data->'value'->'schema_id') AS schema_id,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this also carry ephemeral_owner_session and global_id? Readers need them:

  • Temporary items are Item rows too, and here they get schema_id u0. mz_tables and mz_views report 0 for them, based on ephemeral_owner_session.
  • mz_kafka_sources reads global_id.

Adding columns later would need another replacement step for this MV.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call! Makes sense to me

Comment thread src/catalog/src/builtin/mz_internal.rs Outdated
COALESCE('s' || (data->'value'->>'catalog_id'), '') AS id,
COALESCE('s' || (data->'value'->>'global_id'), '') AS global_id
FROM mz_internal.mz_catalog_state
WHERE kind = 'GidMapping'",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this leave out runtime-alterable builtins, as mz_object_global_ids does with the <RUNTIME-ALTERABLE> fingerprint? mz_internal.mz_analytics (s851) has both a GidMapping and an Item row, so it is in this view and in mz_catalog_items, and readers that combine the two would list it twice.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

/// item kind of the parsed statement, and NULL when the statement does not
/// parse or defines no catalog item.
#[sqlfunc]
fn try_decode_catalog_create_sql<'a>(a: &'a str) -> Jsonb {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing in CI reads rows of the new relations or results of this function, since the goldens pin only plans and names. Could you add an SLT file along these lines?

statement ok
CREATE TABLE t (a INT DEFAULT 1, b TEXT)

statement ok
CREATE VIEW v AS SELECT 'secret' AS s, a FROM t

statement ok
CREATE DEFAULT INDEX ON v

# mz_catalog_items decodes every item the way the existing decoders do.

simple conn=mz_system,user=mz_system
SELECT
    count(*) FILTER (WHERE name IN ('t', 'v', 'v_primary_idx')),
    count(*) FILTER (
        WHERE type IS DISTINCT FROM details->>'type'
        OR details IS DISTINCT FROM mz_internal.parse_catalog_create_sql(create_sql)
        OR redacted_create_sql IS DISTINCT FROM mz_internal.redact_sql(create_sql)
        OR decode_error IS NOT NULL
    )
FROM mz_internal.mz_catalog_items;
----
3,0
COMPLETE 1

# Its identity columns match mz_objects, and every user object is in it.

simple conn=mz_system,user=mz_system
WITH items AS (SELECT id, oid, schema_id, name, owner_id, type FROM mz_internal.mz_catalog_items),
objects AS (SELECT id, oid, schema_id, name, owner_id, type FROM mz_catalog.mz_objects)
SELECT count(*) FROM (
    (SELECT * FROM items EXCEPT ALL SELECT * FROM objects)
    UNION ALL
    (SELECT * FROM objects WHERE id LIKE 'u%' EXCEPT ALL SELECT * FROM items)
);
----
0
COMPLETE 1

# mz_builtin_object_mappings names every builtin object it maps.

simple conn=mz_system,user=mz_system
SELECT count(*) > 800, count(*) FILTER (WHERE o.id IS NULL OR o.name <> m.name OR s.name <> m.schema_name)
FROM mz_internal.mz_builtin_object_mappings m
LEFT JOIN (SELECT DISTINCT id, name, schema_id FROM mz_catalog.mz_objects) o ON o.id = m.id
LEFT JOIN mz_catalog.mz_schemas s ON s.id = o.schema_id;
----
t,0
COMPLETE 1

# Decode failures become data instead of errors.

query T
SELECT mz_internal.try_decode_catalog_create_sql('CREATE MATERIALIZED VIEW "materialize"."public"."mv" AS SELECT 1')::text
----
{"error":"missing IN CLUSTER","type":"materialized-view"}

query T
SELECT mz_internal.try_decode_catalog_create_sql('SELECT 1')::text
----
{"error":"not a CREATE item statement","type":null}

@SangJunBak

Copy link
Copy Markdown
Contributor Author

What's up with the end there? 🤔

Oops! Removed

@SangJunBak
SangJunBak force-pushed the jun/type-relations branch 2 times, most recently from 081441a to 4d7de5c Compare November 18, 2026 23:01
@SangJunBak
SangJunBak requested a review from ggevay November 18, 2026 23:02
ggevay added a commit that referenced this pull request Nov 25, 2026
Closes: [SQL-948](https://linear.app/materializeinc/issue/SQL-948)

### Motivation

During a 0dt upgrade, a builtin storage collection that is new in the
target version gets its shard inside the read-only process's catalog
savepoint, which is never committed, and the promoted leader allocates a
different one. So dataflows that hydrated while read-only are rebuilt at
cut-over, and anything reading a new collection cannot hydrate before
promotion.

On main this hits the three query-policy materialized views from #38762,
which are small leaves. If #40067's `mz_catalog_items` and #40843 on top
of it ship in one upgrade, the 12 catalog-server indexes that depend on
`mz_types` only hydrate after cut-over.

### Description

Reviewable commit by commit:

1. **Shards from the migration shard.** Builtin tables, sources and
materialized views without a shard get theirs from the builtin migration
shard, as `Replacement`-migrated collections do, and the read-only
process writes them the same way.
- An entry is only reused for the same `GlobalId` and builtin. A new
builtin's `GlobalId` exists only in the uncommitted savepoint, and a
later boot can give it to another builtin, for example after another
deploy generation was promoted.
- Versions without the new key field decode these entries and never use
them. Once released, the field must not be reverted or left out of a
backport, or the next version that has it panics on leftover entries.
2. **Leader clock.** For a collection the leader reports no frontier
for, such as a new builtin, the caught-up check compares against the
leader's clock instead of the current time. The clock is the upper of
`mz_cluster_replica_frontiers`, which the leader advances every second.
With the old leader down, as when a region is enabled again after a soft
delete, such a collection's inputs stop, so against the current time it
would lag forever.
3. **New builtins gate promotion.** Only a new storage collection
without a shard from the migration shard still seeds the caught-up
exclusion.
- New views and indexes no longer seed it. Otherwise a new view would
keep everything reading it out of the check, such as `mz_types` and its
indexes, which read #40843's new `mz_builtin_types`. So a new builtin
index over existing collections now has to hydrate before promotion.
- With the break-glass flag `enable_0dt_hydrate_migrated_builtin_mvs`
off, or a leader older than v26.17, every new builtin seeds it, as
before. New tables and sources are written either way.
4. **0dt workflow** `new-builtins-survive-promotion`. It and the two
`builtin-schema-migrations-*` workflows now wait until the replica
reports its reconciliation metrics, since a leader reports `IsLeader`
before it reconnects to its replicas.
5. **Stricter checks in that workflow.** It also compares the
`GlobalId`s of the collections read for the new builtins across the
promotion, because a replica only counts a dataflow as reused or
replaced if it had one with the same ids before. The wait for the
reconciliation metrics ends once two reads in a row agree.
6. **Rename** `migrate_replace` to `get_or_insert_shards`, since it now
also gets shards for collections that had none.
7. **Shorter leader-down run.** The workflow sets the caught-up check's
allowed lag to 10 s on the old leader before stopping it, so that it
only has to wait 20 s instead of 75 s.

The coverage of tables and sources, the matching by both `GlobalId` and
builtin, and the workflow come from Aljoscha's #40904, which fixes the
same bug.

### Verification

- New unit tests for the allocation and matching, the key encoding, and
the leader-clock comparison. Each fails when the behavior it covers is
reverted.
- The new workflow upgrades from v26.17.1, and from v26.47.1 with the
old leader stopped first, after it recorded a `REFRESH` materialized
view's frontier in the future. It checks that the new builtin
materialized views and sources were written on the read-only generation,
promotes, and checks that the collections read for them kept their
`GlobalId`s. With a running leader it also asserts that the catalog
server replaced no dataflow. With the old leader killed, a promotion can
replace dataflows that have nothing to do with new builtins, also on
main, so that run does not assert it. On main the workflow fails,
because the new builtin materialized views are not written on the
read-only generation.
- With #40067 and the PRs stacked on it (through #40900) merged in
locally, a 0dt upgrade from v26.51.0-rc.3 replaces no dataflow. Without
this PR the same upgrade replaces 23: the 12 catalog-server indexes that
read `mz_types`, the dataflows of the new collections, and user
dataflows that read the converted relations.
- Nightly (subsets):
https://buildkite.com/materialize/nightly/builds/18803 (upgrade and 0dt
jobs, on the first four commits) and
https://buildkite.com/materialize/nightly/builds/18805 (0dt jobs, on the
first five commits). On the final head, the new workflow and the two
`builtin-schema-migrations-*` workflows passed locally on the PR's CI
images.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

@ggevay ggevay left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing everything! SQL-948 is fixed on main by #40903, so this is unblocked.

Before merging, could you update the description? It still mentions try_decode_catalog_create_sql and mz_error_if_null (also in the mz_types example), and says that individual SLTs are unnecessary.

One small comment inline.

WHERE ephemeral_owner_session IS NOT NULL;
----
temp_t,u0,t
COMPLETE 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No check reads the new global_id column yet. Maybe add something like this at the end? For most items global_id equals id, so the check uses a replaced materialized view, where the two differ.

# `global_id` is the item's own global id, also where it differs from the catalog id.

simple conn=mz_system,user=mz_system
ALTER SYSTEM SET enable_replacement_materialized_views = true
----
COMPLETE 0

statement ok
CREATE MATERIALIZED VIEW mv AS SELECT count(*) AS c FROM t

statement ok
CREATE REPLACEMENT MATERIALIZED VIEW mv_r FOR mv AS SELECT count(*) + 1 AS c FROM t

statement ok
ALTER MATERIALIZED VIEW mv APPLY REPLACEMENT mv_r

simple conn=mz_system,user=mz_system
SELECT count(*) FILTER (WHERE i.id <> i.global_id), count(*) FILTER (WHERE g.id IS NULL)
FROM mz_internal.mz_catalog_items i
LEFT JOIN mz_internal.mz_object_global_ids g ON g.id = i.id AND g.global_id = i.global_id;
----
1,0
COMPLETE 1

SUPPORT_SELECT,
};

// TODO(SQL-932): every builtin relation but `mz_catalog_state` and the audit

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#40903 has merged, so this is unblocked.

We add a materialized view `mz_catalog_state` that filters out audit log entries. We plan to use this for our other builtin relations such that we don't hydrate from the audit log each time. It would also ensure queries ran outside of mz_catalog_server don't query all of the audit log.
mz_catalog_items is a materialized view over the item records of the durable catalog, derived from mz_catalog_state. Although the additional materialized view creates an additional persist round trip, it saves us from reparsing every item row. 

Since many of our builtin relations join on this relation or don't need the item's DDL text, we create a narrow indexed view that excludes the DDL statement. This way we avoid having to store text-heavy fields in memory.

An issue with having one unified relation is when we call `parse_catalog_create_sql`, one parse failure could poison the entire relation.  Thus we create `try_decode_catalog_create_sql` that  exposes an `ok` and `error` field and allows downstream builtin relations to error via `mz_unsafe.mz_error_if_null`. 

We also need to return the item type even when parsing fails. Thus we extract the `item_type` match statement into a function and reuse it.
Creates mz_internal.mz_builtin_object_mappings, an indexed view over the
builtin GidMapping records of mz_catalog_state. With this and mz_catalog_items, many builtin relations can just be views over a join of these two. Currently all builtin relations define this as a CTE in their own materialized view definition. We ideally want to refactor each of these, but we'll wait until fingerprint changes don't require a builtin replacement.
mz_unsafe.mz_error_if_null raises only when a query evaluates the column
it wraps, and its evaluation order is not guaranteed (SQL-795).  Thus we revert the change of adding `try_decode_catalog_create_sql` and go back to using `parse_catalog_create_sql`.
This is a revert since we no longer need to extract `item_type` as a separate function
Readers of the items layer need both. mz_tables and mz_views report a
temporary item's schema as 0 based on ephemeral_owner_session, and
mz_kafka_sources reads global_id. mz_catalog_item_metadata carries them
too.
…ppings

A runtime-alterable builtin such as mz_internal.mz_analytics has both a
GidMapping record and an Item record, so it was in
mz_builtin_object_mappings and in mz_catalog_items, and a reader
combining the two would list it twice. Filter on the
<RUNTIME-ALTERABLE> fingerprint, as mz_object_global_ids does.
Every other item in the file has a global id equal to its catalog id, so
the check replaces a materialized view to make the two differ.
@SangJunBak
SangJunBak enabled stacked auto-merge (squash) December 1, 2026 23:52
@def-

def- commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

QA LLM Review

1. MEDIUM -- The global ID check passes with two rows for the replaced view

test/sqllogictest/mz_catalog_items.slt:100

The assertion still returns 1,0 if mz_catalog_items emits both the root global ID and the extra version’s global ID for mv. That would give catalog readers two rows for one item while this regression test passes.

Details

For example, with original ID u1 and replacement ID u2, the expected item pair is (u2, u1). The mapping also contains (u2, u2) because mz_object_global_ids includes extra versions (src/catalog/src/builtin/mz_internal.rs:4785). An extra item row carrying that pair contributes to neither count. Assert that exactly one row for mv exists after replacement, alongside the existing ID checks.

@SangJunBak
SangJunBak merged commit da1144a into main Dec 2, 2026
119 checks passed
@SangJunBak
SangJunBak deleted the jun/type-relations branch December 2, 2026 00:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants